#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <jni.h>
#include <stdlib.h>
#include <tchar.h>

//------------------------------------------------------------------------------
static HANDLE			hCom;			// Device COM

static char			cRxBuf[512];
static DWORD			cRxLen;

static BYTE                     bWxBuf[512];
static DWORD                    sendLen, dWxLen;

static DCB dcb;

//------------------------------------------------------------------------------
//int _tmain(  int argc, TCHAR *argv[]           )
  JNIEXPORT jint JNICALL Java_sistcomptf_Comunicador_initRS232C
  (JNIEnv *env, jobject obj, jint COM)
{
   BOOL fSuccess;
   TCHAR *pcCommPort = TEXT("COM");
   char s_ncom[2];
   //int i_ncom=1;


   sprintf( s_ncom, "%i", COM);

   strcat(pcCommPort,s_ncom);

   hCom = CreateFile( pcCommPort,
                    GENERIC_READ | GENERIC_WRITE,
                    0,    // must be opened with exclusive-access
                    NULL, // default security attributes
                    OPEN_EXISTING, // must use OPEN_EXISTING
                    0,    // not overlapped I/O
                    NULL  // hTemplate must be NULL for comm devices
                    );

   if (hCom == INVALID_HANDLE_VALUE) 
   {
       // Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (-1);
   }

   // Build on the current configuration, and skip setting the size
   // of the input and output buffers with SetupComm.

   SecureZeroMemory(&dcb, sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      // Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (-2);
   }

   // Fill in DCB: 9,600 bps, 8 data bits, no parity, and 1 stop bit.

   dcb.BaudRate = CBR_9600;     // set the baud rate
   dcb.ByteSize = 8;             // data size, xmit, and rcv
   dcb.Parity = NOPARITY;        // no parity bit
   dcb.StopBits = ONESTOPBIT;    // one stop bit

   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      // Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (-3);
   }


   return (0);
}
//------------------------------------------------------------------------------
JNIEXPORT jint JNICALL
Java_sistcomptf_Comunicador_sendRS232C(JNIEnv *env, jobject obj, jint COM, jint sendChar)
{
     sendLen = 1;
    bWxBuf[0] = sendChar;

     if (!WriteFile (hCom, bWxBuf,  sendLen, &dWxLen, NULL)){
                return(-1);
        }

     return dWxLen;
}
//------------------------------------------------------------------------------
 JNIEXPORT jint JNICALL
Java_sistcomptf_Comunicador_recvRS232C(JNIEnv *env, jobject obj)
{
     printf("------------->reading............");

     if (!ReadFile (hCom, cRxBuf, 2, &cRxLen, NULL)){
                return(-1);
        }
     printf("------------->read:.....Buf[0]:%x",cRxBuf[0]);
  return cRxBuf[0];
}
//------------------------------------------------------------------------------
 JNIEXPORT jint JNICALL
Java_sistcomptf_Comunicador_test(JNIEnv *env, jobject obj)
{
   DCB dcbs;
   HANDLE hComs;
   char as[2];
   BYTE		bBufs[512];
   BOOL fSuccesss;
   TCHAR *pcCommPorts = TEXT("COM1");
   int javaComs=1;
   DWORD dwLens, js;

   sprintf( as, "%i", javaComs);

   printf("pcCommPort %s\n",pcCommPorts);
   
  //strcat(pcCommPorts,as);

   printf("a %s\n",as);

   printf("pcCommPort:  %s\n",pcCommPorts);


   hCom = CreateFile( pcCommPorts,
                    GENERIC_READ | GENERIC_WRITE,
                    0,    // must be opened with exclusive-access
                    NULL, // default security attributes
                    OPEN_EXISTING, // must use OPEN_EXISTING
                    0,    // not overlapped I/O
                    NULL  // hTemplate must be NULL for comm devices
                    );

   if (hComs == INVALID_HANDLE_VALUE)
   {
       // Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   // Build on the current configuration, and skip setting the size
   // of the input and output buffers with SetupComm.

   SecureZeroMemory(&dcbs, sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);
   fSuccesss = GetCommState(hComs, &dcbs);

   if (!fSuccesss)
   {
      // Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.

   dcbs.BaudRate = CBR_9600;     // set the baud rate
   dcbs.ByteSize = 8;             // data size, xmit, and rcv
   dcbs.Parity = NOPARITY;        // no parity bit
   dcbs.StopBits = ONESTOPBIT;    // one stop bit

   fSuccesss = SetCommState(hComs, &dcbs);

   if (!fSuccesss)
   {
      // Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

   _tprintf (TEXT("Serial port %s successfully reconfigured.\n"), pcCommPorts);

 /* while(1){
   int i;
   for (i=0;i<65534;i++){

   }
       dwLen = 1;
     bBuf[0] = 0x8c;
    */
     printf ("Por leer \n");
     //fSuccess = WriteFile (hCom, bBuf,  dwLen, &j, NULL);
     ReadFile (hComs, bBufs, 2, &dwLens, NULL);

     printf ("Leyo %d bytes. buffer %x", dwLens, bBufs[0]);

   //}

   return (0);
}